package com.ek.kademlia.handlers;

import java.net.InetSocketAddress;
import java.net.SocketAddress;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ek.common.AbstractMessageHandler;
import com.ek.common.Context;
import com.ek.kademlia.protocol.StoreRequest;
import com.ek.kademlia.protocol.impl.DefaultStoreResponse;
import com.ek.service.mina.ComunicationService;

public class StoreRequestHandler extends AbstractMessageHandler<StoreRequest> {
    private static final transient Logger log = LoggerFactory.getLogger(StoreRequestHandler.class);

    public StoreRequestHandler(Context context) {
        super(context);
    }

    @Override
    protected void doExecute(StoreRequest message, SocketAddress address) {
        log.debug("received STORE rpc request from bucket with this socketAddress:" + address + " and this StoreRequest:" + message);
        getContext().getData().put(message.getKey(), message.getValue());
        DefaultStoreResponse response = new DefaultStoreResponse();
        response.setMessageID(message.getMessageID());
        response.setNodeID(getContext().getNodeID());
        InetSocketAddress socketAddress = (InetSocketAddress) address;
        log.debug("sending STORE rpc response to bucket with this socketAddress:" + socketAddress + " and this StoreResponse:" + response);
        getContext().getComunicationService().sendResponse(response, new InetSocketAddress(socketAddress.getAddress(), ComunicationService.PORT));
    }

    public static String getMessageClass() {
        return StoreRequest.class.getCanonicalName();
    }
}
